//makefile makes both this and yours
#include <stdio.h>
#include <glib.h>

int main(){
	GString *buf = g_string_new("");

	gpointer count; //glib pointer for pointer to current count value of word
	gint value;     //glib integer for value
	gpointer k,v;   //glib pointer for key,val when going through hash table and printing words

	GHashTableIter iter; //iterator type looping through hashtable (like dict.items() in python) 
	GHashTable *hist = g_hash_table_new(g_str_hash, g_str_equal);

	GIOChannel *gio = g_io_channel_new_file("justin.txt", "r", NULL);

	while(g_io_channel_read_line_string(gio, buf, NULL, NULL) != G_IO_STATUS_EOF){

		int i = 0;
		gchar **line = g_strsplit(buf->str, " ", 0);

		while(line[i] != '\0'){
			if (g_hash_table_lookup_extended(hist, line[i], NULL, &count)){ 	//looks up word in hashtable and if found it returns true
																				//args: hashtable, key, NULL, pointer variable to store the adress of current word count
				value = GPOINTER_TO_INT(count);	//count is pointer to current word count. This function gets the integer value it points to
				value += 1; //increase by 1
			} else { //if the key doesn't exist in hash table
				value = 1; //set value to 1
			}
			g_hash_table_insert(hist, g_strdup(line[i]), GINT_TO_POINTER(value)); //inserts word, value. Value has to gpointer -> GINT_TO_POINTER() 
			i++;
		}

		g_strfreev(line);
	}

	g_hash_table_iter_init(&iter, hist);//create iterator hashtable
	while (g_hash_table_iter_next(&iter, &k, &v)){ //get next key,val in hashtable. Loop until end is reached
		g_print("%s %i\n", (char *)k, GPOINTER_TO_INT(v)); //print k,v. k,v are gpointer adn have to converted to (char *) and int respectively
		g_free(k); //frees up memory allocated to key
	}

	return 0;
}